﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint;
using MS.InformationManagement.Core.Support;
using MS.InformationManagement.DAL.Support;
using System.Data;

namespace MS.InformationManagement.BLL.ExpedientesList
{
    public class ExpedienteList
    {

        public IEnumerable<Expediente> SearchExpediente(string expediente, int serie, int subserie, DateTime? start, DateTime? end, int pageIndex, int pageSize, out int totalRecords)
        {
            int startingPosition = pageIndex * pageSize; 
            string camlQuery = getExpedienteQuery(expediente, serie, subserie, start, end);
            camlQuery = camlQuery.ToLower() == "<query />" ? string.Empty : camlQuery;
            List<string> viewFields = new List<string>() { CustomSiteColumns.FIELD_EXPEDIENTE_ID, CustomSiteColumns.FIELD_EXPEDIENTE_SUBJECT, "Created", CustomSiteColumns.FIELD_EXPEDIENTE_CODIGO, CustomSiteColumns.FIELD_EXPEDIENTE_END, CustomSiteColumns.FIELD_EXPEDIENTE_START, CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED };
            SPSiteDataQuery query = QuerySiteHelper.getSiteQueryObject(GlobalConstants.GLOBAL_USER_LIBRARY_TEMPLATE, viewFields, camlQuery);
            
            DataTable foundedItems = SPContext.Current.Web.GetSiteData(query);
            var founded = from exp in foundedItems.Rows.OfType<DataRow>()
                          select new Expediente()
                          {
                              NúmeroExpediente = exp[CustomSiteColumns.FIELD_EXPEDIENTE_ID].ToString(),
                              Asunto = exp[CustomSiteColumns.FIELD_EXPEDIENTE_SUBJECT].ToString(),
                              Created = DateTime.Parse(exp["Created"].ToString()),
                              Código = exp[CustomSiteColumns.FIELD_EXPEDIENTE_CODIGO] == null ? null : exp[CustomSiteColumns.FIELD_EXPEDIENTE_CODIGO].ToString(),
                              FechaFinal = string.IsNullOrEmpty(exp[CustomSiteColumns.FIELD_EXPEDIENTE_END].ToString()) ? new Nullable<DateTime>() : DateTime.Parse(exp[CustomSiteColumns.FIELD_EXPEDIENTE_END].ToString()),
                              FechaInicial = string.IsNullOrEmpty(exp[CustomSiteColumns.FIELD_EXPEDIENTE_START].ToString()) ? new Nullable<DateTime>() : DateTime.Parse(exp[CustomSiteColumns.FIELD_EXPEDIENTE_START].ToString()),
                              UsuarioAsignado = exp[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] == null ? string.Empty : exp[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED].ToString()
                          };
            totalRecords = founded.Count();
            founded = (from exp in founded select exp).OrderBy(exp => exp.FechaInicial);
            
            return founded.Skip(startingPosition).Take(pageSize);
        }

        private string getExpedienteQuery(string expediente, int serie, int subserie, DateTime? start, DateTime? end)
        {
            List<string> fields = new List<string>();
            List<string> values = new List<string>();
            List<string> types = new List<string>();
            List<string> operatorTypes = new List<string>();

            //ContentType

            fields.Add(UserLibraryHelper.ContentTypeFieldName);
            values.Add(GlobalConstants.CTTN_EXPEDIENTE);
            types.Add("Text");
            operatorTypes.Add("Eq");

            if (!string.IsNullOrEmpty(expediente))
            {
                fields.Add(CustomSiteColumns.FIELD_EXPEDIENTE_ID);
                values.Add(expediente);
                types.Add("Text");
                operatorTypes.Add("Contains");
            }

            if (serie != 0 && subserie == 0)
            {
                //Get all sub
                var subseries = new BLL.TRDSelector.TRDSelector().GetSubSeries(serie);
                string subSeriesFilter = string.Empty;
                foreach (var subser in subseries)
                  subSeriesFilter += string.IsNullOrEmpty(subSeriesFilter) ? subser.Id.ToString() : ","+subser.Id.ToString();
                fields.Add(CustomSiteColumns.FIELD_EXPEDIENTE_SUBSERIE);
                values.Add(subSeriesFilter.ToString());
                types.Add("Number");
                operatorTypes.Add("In");
            }

            if (subserie != 0)
            {
                fields.Add(CustomSiteColumns.FIELD_EXPEDIENTE_SUBSERIE);
                values.Add(subserie.ToString());
                types.Add("Number");
                operatorTypes.Add("Eq");
            }            

            if (start.HasValue)
            {
                fields.Add(CustomSiteColumns.FIELD_EXPEDIENTE_START);
                //values.Add(SPUtility.FormatDate(SPContext.Current.Web,start.Value.AddMinutes(1), SPDateFormat.ISO8601));
                values.Add(start.Value.ToString(RegularExpresions.ISO8601FORMAT));
                types.Add("DateTime");
                operatorTypes.Add("Geq");
            }

            if (end.HasValue)
            {
                fields.Add(CustomSiteColumns.FIELD_EXPEDIENTE_END);
                //values.Add(SPUtility.FormatDate(SPContext.Current.Web, end.Value.AddMinutes(1), SPDateFormat.ISO8601));
                values.Add(end.Value.ToString(RegularExpresions.ISO8601FORMAT));
                types.Add("DateTime");
                operatorTypes.Add("Leq");
            }
            string temp = string.Empty;
            string query = MS.InformationManagement.Support.CamlHelper.CreateCAMLQuery(values.ToArray(), fields.ToArray(), types.ToArray(), operatorTypes.ToArray(), ref temp);
            return query;
        }
    }
}
